<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Token;
use app\common\library\Wechat;
use app\common\model\CommissionLog;
use app\common\model\factory\Category;
use app\common\model\MoneyLog;
use app\common\model\order\Point;
use app\common\model\ScoreLog;
use app\common\model\shop\Data;
use app\common\model\Survey;
use app\common\model\User as ModelUser;
use app\common\model\user\Address;
use app\common\model\user\Withdrawal;
use app\common\model\Wxpay;
use fast\Random;
use think\Config;
use think\Db;
use think\Log;
use think\Session;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'wxLogin', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }
    /**
     * 门店详情
     *
     */
    public function shop_info()
    {
        $data = ModelUser::get($this->auth->id,['cate']);

        # - 保证金
        $feeorder = \app\common\model\FeeOrder::where(['user_id' => $this->auth->id, 'is_pay' => 1])->find();
        if ($feeorder) {
            $feeorder->visible(['guarantee_fee', 'deduct_fee', 'is_refund', 'days', 'remain_fee', 'device_fee', 'settle_fee', 'manage_fee', 'state']);
            $feeorder->days = max(365 - floor((time() - $feeorder['paytime']) / 86400), 0);
            $feeorder->remain_fee = round($feeorder['guarantee_fee'] - $feeorder['deduct_fee'], 2);
        }

        $data['feeorder'] = $feeorder;

        $this->success('', $data);
    }
    /**
     * 会员中心
     */
    public function index()
    {
        $userInfo = $this->auth->getUser();
        $userInfo['totalMoney'] = MoneyLog::where('type', '2')->where('user_id', $userInfo['id'])->sum('money');
        $userInfo['withdrawal'] = Withdrawal::whereIn('state', ['1', '2'])->where('user_id', $userInfo['id'])->sum('money');
        $userInfo['totalPoint'] = ScoreLog::where('type', '2')->where('user_id', $userInfo['id'])->sum('score');
        $userInfo['usePoint'] = ScoreLog::where('type', '1')->where('user_id', $userInfo['id'])->sum('score');
        $userInfo['team_num'] =  ModelUser::where('pid', $userInfo->id)->count();

        # - 保证金
        $feeorder = \app\common\model\FeeOrder::where(['user_id' => $this->auth->id, 'is_pay' => 1])->find();
        if ($feeorder) {
            $feeorder->visible(['deduct_fee', 'is_refund', 'days', 'remain_fee', 'state', 'items']);
            $feeorder->items = json_decode($feeorder['items'], true);
            $feeorder->days = max(365 - floor((time() - $feeorder['paytime']) / 86400), 0);
            $guarantee_fee = 0;
            foreach ($feeorder['items'] as $k => $v) {
                if ($v['item'] == '保证金') {
                    $guarantee_fee = $v['amount'];
                }
            }

            $feeorder->remain_fee = round($guarantee_fee - $feeorder['deduct_fee'], 2);
        }

        $userInfo['feeorder'] = $feeorder;
        $userInfo->append(['bank_image_text', 'idcard_face_text', 'idcard_emblem_text', 'business_license_text', 'contract_file_text']);
        $this->success('', $userInfo);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $port = $this->request->post('port', 1);
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password, $port);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        // if ($mobile != '15134896935' || $captcha != '1234') {
        //     if (!Sms::check($mobile, $captcha)) {
        //         $this->error(__('Captcha is incorrect'));
        //     }
        // }

        $user = \app\common\model\User::where(['mobile' => $mobile])->where('role', '<>', 'user')->find();
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $mobile, []);
        if ($ret) {
            $this->success(__('Sign up successful'), $this->auth->getUserinfo());
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();

        // $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $code = $this->request->post('code');
        $status = $this->request->post('status', 'normal');
        $business_hours = $this->request->post('business_hours');
        $business_license = $this->request->post('business_license', '');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($nickname) {
            $user->nickname = $nickname;
        }
        if (!$user->pid && $code) {
            $p_user = \app\common\model\User::get(['code' => $code]);
            if (isset($p_user) && !empty($p_user)) {
                $user->pid = $p_user->id;
                $pUser = \app\common\model\User::get($user->pid);
                if ($pUser) {
                    $user->paren_ids = trim($pUser['paren_ids'] . ',' . $user->pid, ',');
                }
            } else {
                $this->error(__('请填写真实邀请码'));
            }
        }
        // $user->bio = $bio;
        if ($business_hours) {
            $user->business_hours = $business_hours;
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }
        if ($status) {
            $user->status = $status;
        }
        if ($business_license) {
            $user->business_license = $business_license;
        }
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }
    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    // public function third()
    // {
    //     $url = url('user/index');
    //     $platform = $this->request->post("platform");
    //     $code = $this->request->post("code");
    //     $config = get_addon_config('third');
    //     if (!$config || !isset($config[$platform])) {
    //         $this->error(__('Invalid parameters'));
    //     }
    //     $app = new \addons\third\library\Application($config);
    //     //通过code换access_token和绑定会员
    //     $result = $app->{$platform}->getUserInfo(['code' => $code]);
    //     if ($result) {
    //         $loginret = \addons\third\library\Service::connect($platform, $result);
    //         if ($loginret) {
    //             $data = [
    //                 'userinfo'  => $this->auth->getUserinfo(),
    //                 'thirdinfo' => $result
    //             ];
    //             $this->success(__('Logged in successful'), $data);
    //         }
    //     }
    //     $this->error(__('Operation failed'), $url);
    // }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $old_password = $this->request->post("old_password");
        $new_password = $this->request->post("new_password");
        $new_password_confirm = $this->request->post("new_password_confirm");
        if (!$new_password || !$old_password || !$new_password_confirm) {
            $this->error(__('Invalid parameters'));
        }

        if ($new_password != $new_password_confirm) {
            $this->error(__('Two passwords are inconsistent'));
        }

        //验证Token
        if (!Validate::make()->check(['newpassword' => $new_password], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }

        $ret = $this->auth->changepwd($new_password, $old_password, false);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 微信小程序登录
     *
     * @params string $openid 唯一标识
     * @params string $sessionKey 秘钥
     * @params string $iv 偏移量
     * @params string $encryptedData 加密串
     * @return array
     */
    public function wxLogin()
    {
        $params = $this->request->param();
        extract($params);

        // 入参
        if (empty($code) ||  empty($phoneCode)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            $wechat = new Wechat('wxMiniProgram');
            $decryptSession = $wechat->code($code);
            if (!isset($decryptSession['session_key'])) {
                exception($decryptSession['errmsg']);
            }
            if (!$decryptSession || !isset($decryptSession['openid'])) {
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptSession['openid'])) {
                exception('code错误,请重试!');
            }
            // 分参
            $decrypt = $wechat->getAccessToken();
            $token = $decrypt['access_token'];
            $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
            $client = new \GuzzleHttp\Client();
            $response = $client->post($url, [
                'json' => [        //参数组
                    'code' => $phoneCode
                ]
            ]);
            $res = $response->getBody();
            $res = json_decode($res, 1);
            if ($res['errcode'] == 0) {
                $phone = $res['phone_info'];
            } else {
                exception('失败:' . $res['errmsg'], $res['errcode']);
            }
            $user = \app\common\model\User::get([
                'openid'   => $decryptSession['openid']
            ]);
            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                $user->save();
                // 直接登陆
                $result = $this->auth->direct($user->id, $token);
            } else {
                if (isset($pid) && !empty($pid)) {
                    $decryptSession['pid'] = $pid;
                }
                $decryptSession['phoneNumber'] = $phone['phoneNumber'];
                $decryptSession['token'] = $token;
                // 写入个人数据
                $result = $this->auth->oauthRegister($decryptSession);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage(), '', $e->getCode());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!' . $this->auth->getError());
        }
    }
    /**
     * 微信App登录
     *
     * @params string $openid 唯一标识
     * @params string $sessionKey 秘钥
     * @params string $iv 偏移量
     * @params string $encryptedData 加密串
     * @return array
     */
    public function wxAppLogin()
    {
        $params = $this->request->param();
        extract($params);
        // 入参
        if (empty($code)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            $wechat = new Wechat('wxAppProgram');
            $decryptData = $wechat->wxAppLogin($code);
            if (!$decryptData || !isset($decryptData['openid']) || !isset($decryptData['unionid'])) {
                Log::error('未获取到登录状态：' . json_encode($decryptData));
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptData['openid']) || empty($decryptData['unionid'])) {
                exception('code错误,请重试!');
            }
            if (isset($decryptData['openid'])) {
                $where['openid'] = ['=', $decryptData['openid']];
            }
            if (isset($decryptData['unionid'])) {
                $where['unionid'] = ['=', $decryptData['unionid']];
            }
            $user = \app\common\model\User::get($where);
            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                // 直接登陆
                $result = $this->auth->direct($user->id);
            } else {
                // 写入个人数据
                if (isset($share_code) && !empty($share_code)) {
                    $p_user = \app\common\model\User::get(['code' => $share_code]);
                    if (isset($p_user) && !empty($p_user)) {
                        $decryptData['pid'] = $p_user['id'];
                    }
                }
                $result = $this->auth->oauthRegister($decryptData);
            }
        } catch (\Exception $e) {
            Log::error('登录失败：' . $e->getMessage());
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!');
        }
    }

    /**
     * 获取用户收货地址
     *
     * @ApiMethod (GET)
     */
    public function getUserAddress()
    {
        $uid = $this->auth->id;
        $data = Address::getUserAddress($uid);
        $this->success('获取成功', $data);
    }
    /**
     * 获取用户默认地址
     *
     * @ApiMethod (GET)
     */
    public function getDefaultAddress()
    {
        $uid = $this->auth->id;
        $list = Address::getDefaultAddress($uid);
        $this->success('获取成功', $list);
    }
    /**
     * 设置用户默认地址
     *
     * @ApiMethod (GET)
     */
    public function setDefaultAddress()
    {
        $id = $this->request->post('id');
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        Address::setDefaultAddress($id, $uid);
        $this->success('设置成功');
    }
    /**
     * 添加收货地址
     *
     * @ApiMethod (GET)
     */
    public function addAddress()
    {
        $post = $this->request->post();
        $validate = validate('user.Address'); //使用助手函数
        $result = $validate->check($post);
        if (!$result) {
            $this->error($validate->getError());
        }
        $post['user_id'] = $this->auth->id;
        $res = Address::AddAddress($post);
        if ($res !== false) {
            $this->success('提交成功', $res);
        }
        $this->error('提交失败');
    }
    /**
     * 删除用户收货地址
     *
     * @ApiMethod (POST)
     */
    public function delAddress()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }
        $id = $this->request->post('id');
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        $data = Address::get($id);
        $data->delete();
        $this->success('删除成功', $data);
    }

    /**
     * 积分兑换记录
     *
     * @ApiMethod (GET)
     */
    public function pointsRecordLog()
    {
        $point = new Point;
        $list = $point->where('user_id', $this->auth->id)->where('status', '<>', '0')->order('id desc')->paginate(10);
        $this->success('', $list);
    }

    /**
     * 用户提现
     *
     */
    public function withdrawal()
    {
        $post = $this->request->post();
        $uid = $this->auth->id;
        $user = $this->auth->getUser();
        if ($this->auth->openid == '') {
            $this->error('请先微信授权', null, 3);
        }

        extract($post);
        Db::startTrans();
        try {
            $post['sn'] = sn('user_withdrawal', 'sn', 'TX');
            $post['user_id'] = $uid;
            $post['money'] = $money;
            $post['mobile'] = $mobile ?? $user->mobile;
            $post['out_batch_no'] = time();
            $post['out_detail_no'] = time() + 5;
            $post['account'] = $this->auth->openid;
            $post['user_role'] = $this->auth->role;

            $tx = new Withdrawal($post);
            $tx->allowField(true)->save();
            MoneyLog::income($uid, $money, 1, 600, $post['sn']);
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('申请成功');
    }
    /**
     * 提现明细
     *
     */
    public function withdrawalInfo()
    {
        $get = request()->get();
        extract($get);
        if (!isset($get) || empty($get)) {
            $this->error('参数错误');
        }
        $tx = new Withdrawal();
        if ($type == 1) {
            $tx->whereTime('createtime', 'month');
        } elseif ($type == 2) {
            $tx->whereTime('createtime', 'week');
        } else {
            if (isset($starttime) && $starttime) {
                $tx->where('createtime', '>', $starttime);
            }
            if (isset($endtime) && $endtime) {
                $tx->where('createtime', '<', $endtime);
            }
        }
        $list = $tx->where('user_id', $this->auth->id)->paginate();
        $this->success('', $list);
    }

    /**
     * 绑定微信
     */
    public function bindWechat()
    {
        $params = $this->request->param();
        extract($params);

        // 入参
        if (empty($code)) {
            $this->error('code 不能为空');
        }

        try {
            $wechat = new Wechat('wxMiniProgram2');
            $decryptSession = $wechat->code($code);
            if (!isset($decryptSession['session_key'])) {
                exception($decryptSession['errmsg']);
            }
            if (!$decryptSession || !isset($decryptSession['openid'])) {
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptSession['openid'])) {
                exception('code错误,请重试!');
            }

            $user = $this->auth->getUser();
            $user->openid = $decryptSession['openid'];
            $user->save();

        } catch (\Exception $e) {
            $this->error($e->getMessage(), '', $e->getCode());
        }

        $this->success('绑定成功');
    }
    /**
     * 用户团队
     *
     */
    public function my_team()
    {
        $get = request()->get();
        extract($get);

        if (isset($keywords) && $keywords) {
            $where['nickname|mobile'] = ['like', '%' . $keywords . '%'];
        }
        $uid = $this->auth->id;
        $where['pid'] = ['=', $uid];
        $users =  ModelUser::where($where)->paginate(10);
        $this->success('', $users);
    }
    /**
     * 积分明细
     *
     */
    public function gsDetails()
    {
        $get = request()->get();
        extract($get);
        if (!isset($type) || !$type) {
            $this->error('参数错误');
        }
        $list = ScoreLog::where('type', $type)->where('user_id', $this->auth->id)->order('id desc')->paginate(10);
        $this->success('', $list);
    }
    /**
     * 佣金明细
     * @ApiMethod (GET)
     * @param string $page   页码
     */
    public function grDetails()
    {
        $get = request()->get();
        extract($get);
        $list = MoneyLog::where('user_id', $this->auth->id)->order('id desc')->paginate(10);

        foreach ($list as $row) {
            if (in_array($row['source_type'], [100, 200, 300, 400, 500])) {
                # - 查看源码好像只有清洗订单和服务订单才有分佣
                $order = \app\common\model\wash\Order::where('fa_wash_order.sn', $row->order_sn)->find();

                if (!$order) {
                    $order = \app\common\model\wash\Serviceorder::where('fa_wash_serviceorder.sn', $row->order_sn)->find();
                }

                $row->order = $order;
            }
        }

        $this->success('', $list);
    }


    /**
     * 余额明细
     * @ApiMethod (GET)
     * @param string $page   页码
     */
    public function commissionlog()
    {
        $get = request()->get();
        extract($get);
        $list = CommissionLog::where('user_id', $this->auth->id)->order('id desc')->paginate(10);
        $this->success('', $list);
    }

    /**
     * 切换门店|驿站
     */
    public function change()
    {
        $uid = $this->request->param('uid', '');
        if ($uid == $this->auth->id) {
            $this->error('当前账号已登录');
        }

        $i = false;
        foreach ($this->auth->list as $v) {
            if ($v['id'] == $uid) {
                $i = true; break;
            }
        }

        if (!$i) {
            $this->error('未查询到账号信息');
        }

        # - 退出当前账号
        $this->auth->logout();

        # - 切换账号
        $ret = $this->auth->change($uid);;
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 证件上传
     */
    public function upload()
    {
        $params = $this->request->only(['idcard_face', 'idcard_emblem', 'business_license', 'contract_file', 'bank_image']);
        # - 字段验证
        $res = $this->validate($params, 'User.upload');
        if ($res !== true) {
            $this->error($res);
        }

        try {
            $user = $this->auth->getUser();
            $user->save($params);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('上传成功');
    }

    /**
     * 佣金明细
     */
    public function commission()
    {
        $list = \app\common\model\MoneyLog::where(['user_id' => $this->auth->id, 'source_type' => ['IN', [100, 200, 300, 400, 500]]])
            ->order('id desc')
            ->paginate(10);

        foreach ($list as $row) {
            # - 查看源码好像只有清洗订单和服务订单才有分佣
            $order2 = $order = \app\common\model\wash\Order::with(['shop' => function ($q) {
                $q->withField('id,nickname,avatar,address,mobile');
            }, 'user' => function ($q) {
                $q->withField('id,nickname,avatar');
            }, 'goods'])
                ->where('fa_wash_order.sn', $row->order_sn)->find();

            if (!$order) {
                $order = \app\common\model\wash\Serviceorder::with(['shop' => function ($q) {
                    $q->withField('id,nickname,avatar,address,mobile');
                }, 'user' => function ($q) {
                    $q->withField('id,nickname,avatar');
                }, 'goods'])
                    ->where('fa_wash_serviceorder.sn', $row->order_sn)->find();
            }

            $row->commission = '-';

            if ($order) {
                $regional = \app\common\model\Admin::get($order['regional_id']);
                if ($regional) {
                    if ($order2) {
                        $total_commission = $regional->total_commission;
                    } else {
                        $total_commission =  $regional->service_total_commission;
                    }

                    # - 总金额先扣除平台佣金，在来计算驿站|门店的佣金分成
                    $money = bcmul($order->pay_fee + $order->money_fee, bcdiv(100 - $total_commission, 100, 2), 2);

                    # - 电话号码中间4位加*
                    $order->phone = substr_replace($order->phone, '****', 3, 4);
                    $row->commission = bcdiv($row->money * 100 , $money, 2) . '%';
                }
            }

            $row->order = $order;
        }

        $this->success('success', $list);
    }
}
